
###########################################################################
#  Copyright 2010 Jim Pulokas
#
#  This file is part of focusfun.
#  
#  focusfun is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  
#  focusfun is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with focusfun.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################


'''
a Grabber object can grab images (currently 640x480 gray) from a 
'''
import gst
import numpack

# N900 uses v4l2camsrc, others may use v4l2src
#src_element = 'v4l2src'
src_element = 'v4l2camsrc'

class Grabber(object):
	def __init__(self, device):
		launchstr = '''
			%s name=v4l2src device="%s" !
			ffmpegcolorspace name=converter !
			video/x-raw-gray,bpp=8,width=640,height=480 !
			appsink name=appsink max-buffers=2 sync=False
		''' % (src_element, device,)

		self.player = gst.parse_launch(launchstr)

		self.v4l2src = self.player.get_by_name('v4l2src')
		self.converter = self.player.get_by_name('converter')
		self.appsink = self.player.get_by_name('appsink')
		self.finalsrc = self.converter.get_static_pad('src')

		self.player.set_state(gst.STATE_PLAYING)

		self.v4l2_fd = self.v4l2src.get_property('device-fd')

	def grab_buffer(self):
		buffer = self.appsink.emit('pull-buffer')
		return buffer

	def grab(self):
		buffer = self.grab_buffer()
		caps = self.finalsrc.get_negotiated_caps()
		structure = caps[0]
		width = structure['width']
		height = structure['height']
		shape = (height, width)
		a = numpack.buffer_to_array(buffer, shape)
		return a

	def grab_to_file(self, filename):
		im = self.grab()
		pil_image = numpack.array_to_image(im)
		pil_image.save(filename)

def test():
	g = Grabber('/dev/video0')
	a = g.grab()
	print 'Shape:', a.shape
	print 'First few elements:', a[0][:10]

if __name__ == '__main__':
	test()
